package com.jingdianjichi.auth.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.jingdianjichi.auth.common.entity.Result;
import com.jingdianjichi.auth.convert.AuthUserDTOConverter;
import com.jingdianjichi.auth.domin.entity.AuthUserBO;
import com.jingdianjichi.auth.domin.service.AuthUserDomainService;
import com.jingdianjichi.auth.dto.AuthUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user/")
@Slf4j
public class UserController {

    @Resource
    private AuthUserDomainService authUserDomainService;

    //盐值
    private String salt = "chicken";

    /**
     * @Description: 注册用户
     * @return:
     * @Author:  sky
     * @date:  2024/11/11 0:02
     */
    @RequestMapping("register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO) {
        try {
            // 判断是否启动info级别的日志，如果启动了再执行json转换，减少性能开销
            if(log.isInfoEnabled()){
                log.info("log-info:{}", JSON.toJSONString(authUserDTO));
            }

            // 字符串需要同时检测， null 和 空串 两种情况，断言匹配false抛出异常
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()),"用户名不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getEmail()),"邮件不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getPassword()),"密码不能为空");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);
            // alt + enter 快速生成返回变量
            return Result.success(authUserDomainService.register(authUserBO));
        }catch (Exception e){
            log.error("log-error:{}",e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    /**
     * @Description: 更新用户
     * @return:
     * @Author:  sky
     * @date:  2024/11/11 0:02
     */
    @RequestMapping("update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDTO) {
        try {
            // 判断是否启动info级别的日志，如果启动了再执行json转换，减少性能开销
            if(log.isInfoEnabled()){
                log.info("log-info:{}", JSON.toJSONString(authUserDTO));
            }

            // 字符串需要同时检测， null 和 空串 两种情况，断言匹配false抛出异常
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()),"用户名不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getEmail()),"邮件不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getPassword()),"密码不能为空");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);
            // alt + enter 快速生成返回变量
            return Result.success(authUserDomainService.update(authUserBO));
        }catch (Exception e){
            log.error("log-error:{}",e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    /**
     * @Description: 获取用户信息
     * @return:
     * @Author:  sky
     * @date:  2024/11/11 0:02
     */
    @RequestMapping("getUserInfo")
    public Result<AuthUserDTO> getUserInfo(@RequestBody AuthUserDTO authUserDTO) {
        try {
            // 判断是否启动info级别的日志，如果启动了再执行json转换，减少性能开销
            if(log.isInfoEnabled()){
                log.info("log-info:{}", JSON.toJSONString(authUserDTO));
            }

            // 字符串需要同时检测， null 和 空串 两种情况，断言匹配false抛出异常
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()),"用户名不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getEmail()),"邮件不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getPassword()),"密码不能为空");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);
            AuthUserBO userInfoBO = authUserDomainService.getUserInfo(authUserBO);
            AuthUserDTO userInfoDTO = AuthUserDTOConverter.INSTANCE.convertBOToDTO(userInfoBO);
            // alt + enter 快速生成返回变量
            return Result.success(userInfoDTO);
        }catch (Exception e){
            log.error("log-error:{}",e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    /**
     * @Description: 删除用户
     * @return:
     * @Author:  sky
     * @date:  2024/11/11 0:02
     */
    @RequestMapping("delete")
    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDTO) {
        try {
            // 判断是否启动info级别的日志，如果启动了再执行json转换，减少性能开销
            if(log.isInfoEnabled()){
                log.info("log-info:{}", JSON.toJSONString(authUserDTO));
            }

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);
            // alt + enter 快速生成返回变量
            return Result.success(authUserDomainService.delete(authUserBO));
        }catch (Exception e){
            log.error("log-error:{}",e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    /**
     * @Description: 用户的启用/禁用
     * @return:
     * @Author:  sky
     * @date:  2024/11/11 0:02
     */
    @RequestMapping("changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDTO) {
        try {
            // 判断是否启动info级别的日志，如果启动了再执行json转换，减少性能开销
            if(log.isInfoEnabled()){
                log.info("log-info:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getStatus(),"用户状态不能为空");
            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);
            // alt + enter 快速生成返回变量
            return Result.success(authUserDomainService.update(authUserBO));
        }catch (Exception e){
            log.error("log-error:{}",e.getMessage());
            return Result.fail(e.getMessage());
        }
    }





    /**
     * 用户登录接口
     */
    @RequestMapping("doLogin")
    public SaResult doLogin(@RequestBody AuthUserDTO authUserDTO) {
        try {
            // 日志记录
            if (log.isInfoEnabled()) {
                log.info("用户登录请求: {}", JSON.toJSONString(authUserDTO));
            }

            // 参数校验
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()), "用户名不能为空");
            Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getPassword()), "密码不能为空");

            // 转换为 BO 对象并查询用户信息
            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTOToBO(authUserDTO);
            AuthUserBO userInfoBO = authUserDomainService.getUserInfo(authUserBO);

            // 判断用户是否存在
            if (userInfoBO == null) {
                return SaResult.error("登录失败：用户不存在");
            }

            // 验证密码（假设数据库中存储的是明文密码，实际应使用加密处理）
            if (!SaSecureUtil.md5BySalt(authUserDTO.getPassword(),salt).equals(userInfoBO.getPassword())) {
                return SaResult.error("登录失败：密码错误");
            }

            // 密码验证通过，执行登录操作
            StpUtil.login(userInfoBO.getId()); // 使用用户ID作为登录标识
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

            return SaResult.data(tokenInfo);

        } catch (Exception e) {
            log.error("登录异常", e);
            return SaResult.error("登录失败：" + e.getMessage());
        }
    }



    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }




}


